<?php

class Registrasi extends CI_Controller {

    var $_public_view;

    function __construct() {
        parent::__construct();
        $this->load->model('model_perjalanan', 'mtrip');
        $this->load->helper('url');
        $this->load->library('session');
        $this->config->load('ojexcom');
        $this->_public_view = $this->config->item('public_view');
    }

    function index() {
        //cek session
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        $data = array(
            'isLogin' => $isLogin, 'user' => $user, 'id' => $id,
            'page_title' => 'O-JEX',
            'page_content' => 'register');
       $this->load->view($this->_public_view, $data);
    }

    function daftar(){ 
        $data_output['success'] = "false";
        $error = 0;
        $username = $this->input->post('username'); 
        
        if($username!=NULL){
            if($this->checkAvailableUsername($username) == true){
                $query_username = $this->db->query("SELECT COUNT(username) AS count FROM `user` WHERE username = '".$username."'");
                $row_username = $query_username->row();
                if($row_username->count >0)             $error = 3;
            }else{
                $error = 3;
            }
        }else           $error = 99;
        
        $phoneNumber = $this->input->post('phoneNumber');
        if($error == 0 && $phoneNumber!=NULL){
            if($this->checkAvailablePhone($phoneNumber) == true){
                
                $query_phoneNumber = $this->db->query("SELECT COUNT(phoneNumber) AS count FROM `userprofile` WHERE phoneNumber = '".$phoneNumber."'");
                $row_phoneNumber = $query_phoneNumber->row();
                if($row_phoneNumber->count > 0)         $error = 1;
            }else{
                $error = 1;
            }
        }
        
        $email = $this->input->post('email');
        if($error == 0 && $email!=NULL){
            if($this->checkAvailableEmail($email) == TRUE){
                $query_email = $this->db->query("SELECT COUNT(email) AS count FROM `userprofile` WHERE email = '".$email."'");
                $row_email = $query_email->row();
                if($row_email->count > 0)               $error = 2;
            }else           $error = 2;
        } 
        
        if($error == 0){
            $today = date("Y-m-d H:i:s");
            $input_data = array(
                'username' => $username,
                'name' => $this->input->post('name'),
                'password' => md5($this->input->post('password')),
                'isPremium' => "0",
                'entryDate' => $today,
                'lastUpdated' => $today,
                'gender' => $this->input->post('gender'),
            );      
            $this->db->insert('user', $input_data); 
            
            if($this->db->affected_rows() < 1)              $error = 99;
            
        } 
        $userID = 0;
        if($error == 0){
            $query = $this->db->query("SELECT `id` FROM `user`WHERE username='".$username."'");
            $row = $query->row();
            $userID = $row->id;
            $input_data = array(
                'idUser' => $userID,
                'phoneNumber' => $phoneNumber,
                'email' => $email,
            );      
            $this->db->insert('userprofile', $input_data);
            if($this->db->affected_rows() < 1)              $error = 99;
        }
        
        if($error == 0){
            $data_output['success'] = "true";
            $data_output['id'] = "".$userID;
        }else{
            $data_output['success'] = "false";
            $data_output['error'] = "".$error;
        }
        
        // header('Content-Type: application/json');
        // echo json_encode($data_output);
        //$username = $this->input->post('username');
        $password = $this->input->post('password');
        if($username != NULL){
            $query = $this->db->query("SELECT `id`, name, isPremium FROM `user` WHERE username='".$username."' AND password='".md5($password)."'");
            $row = $query->row();
            if($query->num_rows() > 0){
                $data_output['success'] = "true";
                $data_output['id'] = $row->id;
                $data_output['name'] = $row->name;
                $data_output['isPremium'] = $row->isPremium."";

                //set session
                $this->session->set_userdata('isLogin', true);
                $this->session->set_userdata('username', $username);
                $this->session->set_userdata('user_id',$row->id);
                $this->session->set_userdata('isPremium',$row->isPremium);
            } else {
                $data_output['success'] = "false";
                $this->session->set_userdata('page','login');
                $data = array('page_content' => 'login', 'page_title' =>'LOG IN','isLogin'=>'',
                    'error'=>'username atau password salah');
                $this->load->view($this->_public_view, $data);
            }
            
            $ios_token = $this->input->post('ios_token');
            if($ios_token != NULL) {
                $input_data = array(
                    'ios_token' => $ios_token
                );
                $this->db->where('id', $row->id);
                $this->db->update('user', $input_data);
            }
        } else {
            $data_output['success'] = "false";
            $this->session->set_userdata('page','login');
            $data = array('page_content' => 'login', 'page_title' =>'LOG IN',
                'error' => 'username dan password harus diisi',
                'isLogin'=>'');
            $this->load->view($this->_public_view, $data);
        }

        if($data_output['success']=="true"){
            $id = $this->session->userdata('user_id');
            $this->session->unset_userdata('page');
        $data = array('page_content' => 'home', 'page_title' =>'O-JEX',            
                    'output' => $this->mtrip->get(),
                    'user' => $this->session->userdata('username'), 
                    'isLogin' => $this->session->userdata('isLogin'),
                    'id'=>$this->session->userdata('user_id'));
        $this->load->view($this->_public_view, $data); //tampilkan datanya
        }
                
    }
    
    function checkAvailableUsername($username){
        
        $url = 'http://indobarter.com/api/index.php/api/ojegapi/cekusername/username/'.$username;
        
        $options = array(
            'http' => array(
                'header'=>  "Content-Type: application/json\r\n" .
                "Accept: application/json\r\n"
            )
        );

        $context  = stream_context_create( $options );
        $result = file_get_contents( $url, true, $context );
        $response = json_decode( $result , true);
        if(!empty($response['status']))         return true;
        else            return false;
    
    }
    
    function checkAvailableEmail($email){
        
        $url = 'http://indobarter.com/api/index.php/api/ojegapi/cekemail/emailid/'.str_replace($email, '@', '/server/');
        
        $options = array(
            'http' => array(
                'header'=>  "Content-Type: application/json\r\n" .
                "Accept: application/json\r\n"
            )
        );

        $context  = stream_context_create( $options );
        $result = file_get_contents( $url, true, $context );
        $response = json_decode( $result , true);
        if(!empty($response['status']))         return true;
        else            return false;
    
    }
    
    function checkAvailablePhone($phone){
        
        $url = 'http://indobarter.com/api/index.php/api/ojegapi/ceknorekening/norekening/'.$phone;
        
        $options = array(
            'http' => array(
                'header'=>  "Content-Type: application/json\r\n" .
                "Accept: application/json\r\n"
            )
        );

        $context  = stream_context_create( $options );
        $result = file_get_contents( $url, true, $context );
        $response = json_decode( $result , true);
        if(!empty($response['status']))         return true;
        else            return false;
    
    }

}

?>
